import React, {useEffect, useState} from "react";
import {
  Skeleton,
  Table,
  Avatar,
  Input,
  Space,
  Button,
  Tag,
  Form,
  Col,
  Row,
  Select,
  DatePicker,
  Cascader,
  Radio, message, Popconfirm
} from "antd";
import {PageData, PaperPo} from "../../../../types";
import {fetch, MethodEnum, Navigation} from "f22";
import {ColumnsType} from "antd/lib/table";
import {diSubjects, SubjectPo} from "../../subject/SubjectManage";
import moment from "moment"


export default () => {

  const columns: ColumnsType<PaperPo> = [
    {
      title: '试卷编号',
      dataIndex: 'id',
    },
    {
      title: '试卷名称',
      dataIndex: 'paperName',
    },
    {
      title: '学科',
      dataIndex: 'subjectName',
    },
    {
      title: '试卷年份(年)',
      dataIndex: 'year',
    },
    {
      title: '考试时长(分钟)',
      dataIndex: 'time',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '试卷类型',
      dataIndex: 'paperTypeId',
      render: (text) => {
        if (text === 1) return "历年真题"
        if (text === 2) return "模拟试题"
        if (text === 3) return "每日一练"
      }
    },
    {
      title: '发布状态',
      dataIndex: 'releaseStatus',
      render: (text) => {
        if (text == 0) return <Tag color="magenta">未发布</Tag>
        if (text == 1) return <Tag color="green">已发布</Tag>
      }
    },
    {
      title: "操作",
      dataIndex: 'releaseStatus',
      align: "center",
      render(text, record, index) {
        if (text == 0) {
          return (<>
            <Popconfirm title="确定要发布吗?" onConfirm={() => changeReleaseStatus(record.id, 1)}>
              <Button type="primary">发布</Button>
            </Popconfirm>
            <Button style={{marginLeft: "8px"}}
                    type="default" onClick={() => Navigation.push(`/PaperEdit/${record.id}`)}>编辑</Button>
          </>)
        }

        if (text == 1) {
          return (
            <>
              <Popconfirm title="确定要撤销发布吗?" onConfirm={() => changeReleaseStatus(record.id, 0)}>
                <Button type="primary"
                        danger>撤销发布</Button>
              </Popconfirm>
              <Button style={{marginLeft: "8px"}}
                      type="default" onClick={() => Navigation.push(`/PaperView/${record.id}`)}>查看</Button>
            </>
          )
        }
      }
    }
  ];

  const [data, setData] = useState<PageData<PaperPo> | null>(null);
  const [subjectData, setSubjectData] = useState<SubjectPo[]>([])
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [form] = Form.useForm();
  const [search, setSearch] = useState<any>({
    subjectId: "",
    paperTypeId: "",
    paperName: "",
    year: "",
    releaseStatus: "0"
  });
  const [refreshtag, setRefreshTag] = useState(0);

  // 变更发布状态
  const changeReleaseStatus = async (id: number, releaseStatus: number) => {
    await fetch({
      url: `/admin/paper/${id}/changeReleaseStatus/${releaseStatus}`,
      method: MethodEnum.PUT,
    })
    message.success("状态变更成功")
    setRefreshTag(t => t + 1)
  }
  // 搜索
  const onFinish = values => {
    const r = Object.keys(values).reduce((container, key) => {
      const value = values[key]
      if (key === "releaseStatus" && !value) return {...container, [key]: "0"}
      if (!value || (Array.isArray(value) && !value.length)) return {...container, [key]: ""}
      if (Array.isArray(value) && value.length) return {...container, [key]: value[value.length - 1]}
      if (moment.isMoment(value)) return {...container, [key]: value.get("year")}
      return {...container, [key]: value}
    }, {})
    setSearch(r);
  };

  // 列表数据
  useEffect(() => {
    fetch({
      url: "/admin/paper/list",
      method: MethodEnum.GET,
      request: {
        page,
        pageSize,
        ...search
      }
    }).then(data => {
      setData(data.response)
    })
  }, [page, pageSize, search, refreshtag])

  // 学科数据
  useEffect(() => {
    fetch<SubjectPo[]>({
      method: MethodEnum.GET,
      url: "/subject/all"
    }).then(data => {
      setSubjectData(diSubjects(data.response))
    })
  }, [])


  if (data == null || !subjectData.length) return <Skeleton/>
  return <>
    <Form
      form={form}
      name="advanced_search"
      className="ant-advanced-search-form"
      onFinish={onFinish}
    >
      <Row gutter={24}>
        <Col span={4}>
          <Form.Item
            name={`subjectId`}
            label={`所属学科`}
          >
            <Cascader options={subjectData} placeholder="请选择学科"/>
          </Form.Item>
        </Col>
        <Col span={4}>
          <Form.Item
            name={`paperTypeId`}
            label={`试卷类型`}
          >
            <Select placeholder="请选择试卷类型" allowClear>
              <Select.Option value={1}>历年真题</Select.Option>
              <Select.Option value={2}>模拟试题</Select.Option>
              <Select.Option value={3}>每日一练</Select.Option>
            </Select>
          </Form.Item>
        </Col>
        <Col span={4}>
          <Form.Item
            name={`paperName`}
            label={`试卷名称`}
          >
            <Input placeholder="请输入试卷名称" allowClear/>
          </Form.Item>
        </Col>
        <Col span={4}>
          <Form.Item
            name={`year`}
            label={`年份`}
          >
            <DatePicker picker="year" allowClear/>
          </Form.Item>
        </Col>
        <Col span={4}>
          <Form.Item
            name={`releaseStatus`}
            label={`状态`}
          >
            <Radio.Group defaultValue={"0"} buttonStyle="solid">
              <Radio.Button value="0">未发布</Radio.Button>
              <Radio.Button value="1">已发布</Radio.Button>
            </Radio.Group>
          </Form.Item>
        </Col>
        <Col style={{textAlign: "left"}} span={4}>
          <Button type="primary" htmlType="submit">
            搜索
          </Button>
          <Button
            style={{margin: '0 8px'}}
            onClick={() => {
              form.resetFields();
            }}
          >
            重置
          </Button>
        </Col>
      </Row>
    </Form>
    <Table<PaperPo>
      bordered
      dataSource={data?.records}
      columns={columns}
      rowKey={(r) => r.id}
      pagination={
        {
          pageSize: pageSize,
          pageSizeOptions: ["10", "20", "50"],
          total: data.total,
          showTitle: true,
          current: page,
          onChange(p, ps) {
            if (p !== page) setPage(p)
            if (ps !== pageSize && !!ps) setPageSize(ps)
          }
        }
      }/></>;
}
